﻿using MiniFox.Infrastructure;
using MiniFox.Net;
using MiniFox.Net.Http;
using MiniFox.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForWebApi.Models;

namespace WinForWebApi
{
    public partial class EditForm : Form
    {
        readonly HttpAdapter httpAdapter;
        string deviceId;
        public EditForm(string deviceId)
        {
            this.deviceId = deviceId;
            InitializeComponent();
            var container = WebAdapterFactory.Container;
            this.httpAdapter = container.GetHttpAdapterByName("device");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var requestObj = new DeviceDto
            {
                deviceId = this.deviceId,
                snCode = this.txtSnCode.Text,
                displayCode = this.txtDisplayCode.Text,
                deviceName = this.txtDeviceName.Text,
                deviceType = this.txtDeviceType.Text
            };

            var service = this.httpAdapter.GetService(string.IsNullOrEmpty(this.deviceId)? "create":"update");
            var task = service.PostAsync<DeviceDto, Response<DeviceVo>>(requestObj);
            var response = await task;

            if (response.Success)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private async void EditForm_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.deviceId))
            {
                this.txtSnCode.Text = Tools.GenerateRandomCode(20);
                this.txtDisplayCode.Text = Tools.GenerateRandomCode(10);
                this.txtDeviceName.Text = Tools.GenerateRandomCode(20);
                this.txtDeviceType.Text = Tools.GenerateRandomCode(5);
            }
            else
            {
                var service = this.httpAdapter.GetService("get");
                var task = service.GetAsync<Response<DeviceVo>>(new { deviceId = deviceId });
                var response = await task;
                var deviceVo = response.Data;

                this.txtSnCode.Text = deviceVo.snCode;
                this.txtDisplayCode.Text = deviceVo.displayCode;
                this.txtDeviceName.Text = deviceVo.deviceName;
                this.txtDeviceType.Text = deviceVo.deviceType;

            }
        }
    }
}
